// gulpfile.js

const { dest } = require('gulp')
const gulp = require('gulp'),
      htmlmin = require('gulp-htmlmin'),
      cleanCss = require('gulp-clean-css'),
      autoprefixer = require('gulp-autoprefixer'),
      uglify = require('gulp-uglify'),
      babel = require('gulp-babel'),
      del = require('del'),
      connect = require('gulp-connect'),
      { createProxyMiddleware } = require('http-proxy-middleware'),
      sass = require('gulp-sass')

  

// createProxyMiddleware()

// gulp.task 以前3的用法

// 提前规划所有文件的路径
const paths = {
  html: {
    src: 'src/**/*.html',
    dest: 'dist'
  },
  css: {
    src: 'src/css/**/*.scss',
    dest: 'dist/css'
  },
  js: {
    src: 'src/js/**/*.js',
    dest: 'dist/js'
  },
  libs:{
    src: 'src/libs/**/*',
    dest: 'dist/libs'
  },
  img:{
    src: 'src/img/**',
    dest: 'dist/img'
  }

}



const delDist = ()=>{return del('dist')}

// 指定html任务：压缩html，从src里把html文件取出来，然后压缩，最后放进dist目录
const html = () => {
  // ** 代表所有目录，*代表所有文件
  return gulp.src(paths.html.src)
    .pipe(htmlmin({
      removeComments: true, // 清除HTML注释
      collapseWhitespace: true, // 压缩HTML
      collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input checked />
      removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
      removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
      removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
      minifyJS: true,//压缩页面JS
      minifyCSS: true//压缩页面CSS 
    }))
    .pipe(gulp.dest(paths.html.dest))
    .pipe(connect.reload())
}

// 制定css任务：先给css3一些样式加上前缀，再压缩css
const css = ()=>{
    return gulp.src(paths.css.src)
        .pipe(sass())
        .pipe(autoprefixer({
            cascade:false
        }))
        .pipe(cleanCss())
        .pipe(gulp.dest(paths.css.dest))
        .pipe(connect.reload())
}
const js = () => {
  return gulp.src(paths.js.src)
    .pipe(babel({
      presets: ['@babel/env']
    }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.js.dest))
    .pipe(connect.reload())
}
const img = ()=>{
  return gulp.src(paths.img.src).pipe(gulp.dest(paths.img.dest))
}

const libs = ()=>{
  return gulp.src(paths.libs.src).pipe(gulp.dest(paths.libs.dest))
}

//制定一个服务器
const server = ()=>{
  connect.server({
    root:'dist',
    port:2333,
    livereload:true,
    middleware(){
      return [
        createProxyMiddleware('/api',{
          target:'https://apiv2.pinduoduo.com',
          changeOrigin:true
        })
      ]
      
    }
  })
}

//watch  监听文件的改变，文件修改可以重启对应的任务
const watch = ()=>{
  gulp.watch(paths.html.src,html)
  gulp.watch(paths.css.src,css)
  gulp.watch(paths.js.src,js)
  gulp.watch(paths.img.src,img)
}

// 把制定好的任务导出
// module.exports = {
//   html,
//   css,
//   js,
//   img,
//   libs
// }


//同步执行所有
module.exports.default = gulp.series(delDist,gulp.parallel(html,css,js,libs,img,server,watch))

